package com.fafu;


import com.fafu.model.Manager;
import com.fafu.model.Student;
import com.fafu.pojo.ManagerInfoPojo;
import com.fafu.service.StudentService;
import com.fafu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import util.Dictionary;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

//@Component
public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;
    @Autowired
    private StudentService studentService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        // 只有返回true才会继续向下执行，返回false取消当前请求
        /**
         * 查询用户，查询用户是否有操作权限
         */
        Map map = userService.getUserIdStr(request);
        String id = (String) map.get("data");
        if(id==null || id.equals("-1")) return false;//没有登录
        String[] ids = id.split("\\.");
        System.out.println("拦截");
        if(ids[0].equals("manager")) {
            //检查管理员的isused;
            Manager manager = userService.getUserInfoModel(Integer.valueOf(ids[1]));
            if(manager.getIsUsed() == Dictionary.MANAGER.MANAGER_NOT_USER)
                return false;
        }else{//检查学生的isused
            Map<String,Object> remap = studentService.getStudentById(Integer.valueOf(ids[1]));
            Student student = (Student) remap.get("data");
            if(student.getIsUsed() == Dictionary.MANAGER.MANAGER_NOT_USER)
                return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
